package com.mask.mk.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.mask.mk.mapper.*;
import com.mask.mk.pojo.*;
import com.mask.mk.service.GOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mask.mk.util.JsonResult;
import com.mask.mk.vo.order.AddOrderRequest;
import com.mask.mk.vo.order.OrderCheckPageResponse;
import com.mask.mk.vo.order.OrderResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * <p>
 * 订单表 服务实现类
 * </p>
 *
 * @author joey
 * @since 2023-04-25
 */
@Service
public class GOrderServiceImpl implements GOrderService {

    @Autowired
    private GOrderMapper gOrderMapper;

    @Autowired
    private OrderDetailMapper detailMapper;

    @Autowired
    private GoodsMapper goodsMapper;

    @Autowired
    private MUserMapper mUserMapper;

    @Autowired
    private AddressinfoMapper addressinfoMapper;

    //随机颜色
    public String randomColor(){
        String[] colorList = {"黑", "绿", "蓝", "米白", "彩", "紫"};

        int length = 1; // 生成的字符串长度
        Random random = new Random();
        StringBuilder sb = new StringBuilder();

        for (int i = 0; i < length; i++) {
            int index = random.nextInt(colorList.length);
            sb.append(colorList[index].charAt(0)); // 取颜色名的首字母
        }

        String randomString = sb.toString();
        System.out.println("Generated random string: " + randomString+"色");
        return randomString+"色";
    }


    @Override
    @Transactional(rollbackFor=Exception.class)
    public JsonResult addOrder(AddOrderRequest addOrderRequest) {

        JsonResult result = null;
        // 订单表
        // 订单id、用户id、总价格、商品数量、支付方式、收货地址id、订单状态、订单创建时间、订单付款时间、订单完成时间、更新时间
        if(addOrderRequest!=null){
            if(addOrderRequest.getOrderStatus()==0){ //进入结算页面时生成订单 状态为未支付 -> 0
                //订单id 用户id 总价格 商品数量 订单状态 订单创建时间
                GOrder gOrder = new GOrder();
                gOrder.setUid(addOrderRequest.getUserId())
                        .setTotalPrice(addOrderRequest.getGoodsTotalPrice())
                        .setGoodsNum(addOrderRequest.getGoodsNum())
                        .setStatus(addOrderRequest.getOrderStatus());
                int OrderInsert = gOrderMapper.insert(gOrder);
                if(OrderInsert>0){
                    // 订单详情表
                    // 订单详情id、订单id、用户id、用户手机号、用户姓名、商品id、商品名称、商品价格、商品颜色、商品尺码、商品数量

                    //获取用户信息
                    MUser mUser = mUserMapper.selectById(addOrderRequest.getUserId());
                    //循环商品id 添加商品详情
                    OrderDetail orderDetail = null;
                    int i =0;

//                    Random rcolor = new Random();
                    System.out.println("商品单个数量：=>" + addOrderRequest.getGoodsOwnNum());
                    for (Integer goodsId : addOrderRequest.getGoodsIdList()) {
                        Goods goods = goodsMapper.selectById(goodsId);
                        delGoodsNum(goodsId);
                        if(goods!=null){
                            orderDetail = new OrderDetail();
                            orderDetail.setGoodscolor(randomColor()) //随机颜色
                                    .setOid(gOrder.getOid())
                                    .setGoodssize("L")
                                    .setGoodsid(goods.getGid())
                                    .setGoodsname(goods.getGname())
                                    .setUserid(addOrderRequest.getUserId())
                                    .setUsername(mUser.getUserName())
                                    .setUserphone(mUser.getPhone())
                                    .setGoodsnum(addOrderRequest.getGoodsOwnNum().get(i))
                                    .setGoodsPic(goods.getImgLink())
                                    .setGoodsprice(goods.getGprice() * addOrderRequest.getGoodsOwnNum().get(i));

                            int i1 = detailMapper.insert(orderDetail);
                            if(i1>0){
                                i++;
                            }else{
                                System.out.println("插入失败");
                            }
                        }else{
                            System.out.println("商品查询为空");
                        }
                    }
                    OrderDetail detail = detailMapper.selectById(orderDetail.getOdid());
                    result = JsonResult.success(detail);
                }else{
                    System.out.println("生成订单- 第一阶段失败");
                }
            }else if(addOrderRequest.getOrderStatus()==1){ //已付款 生成待收货订单
                //todo 待写 已付款后更新订单

                GOrder gOrder = gOrderMapper.selectById(addOrderRequest.getOrderId());

                Addressinfo addressinfo1 = addressinfoMapper.selectById(addOrderRequest.getAddressId());
                int insert =0;

                // 当有默认地址时 查询地址状态 是否修改为默认
                if(addressinfo1!=null){ //不为空更新
                    if(addOrderRequest.getAddressDefault()==1){//如果设为默认地址 其余地址置为其他
                        updateAddress(addOrderRequest.getUserId());
                    }
                    //地址更新
                    addressinfo1.setUserName(addOrderRequest.getUserName())
                            .setUserid(addOrderRequest.getUserId())
                            .setUserPhone(addOrderRequest.getUserPhone())
                            .setDefaultStatus(addOrderRequest.getAddressDefault())//状态
                            .setAdinfo(addOrderRequest.getAddressInfo())
                            .setDetailInfo(addOrderRequest.getAddressDetailInfo());
//                    delGoodsNum();

                    insert = addressinfoMapper.updateById(addressinfo1);
                    if(insert>0){
                        gOrder.setStatus(1)
                                .setAddressId(addressinfo1.getAddressid())
                                .setCheckTime(new Date())
                                .setPayWay(addOrderRequest.getPayWay());
                        int updateById = gOrderMapper.updateById(gOrder);
                        if(updateById>0){
                            result = JsonResult.success(gOrder);
                        }else{
                            result = JsonResult.fail("修改订单异常");
                        }
                    }else{
                        result = JsonResult.fail("添加地址信息异常");
                    }
                }else{//为空新增
                    Addressinfo addressinfo = new Addressinfo();
                    //地址添加
                    addressinfo.setUserName(addOrderRequest.getUserName())
                            .setUserid(addOrderRequest.getUserId())
                            .setUserPhone(addOrderRequest.getUserPhone())
                            .setDefaultStatus(addOrderRequest.getAddressDefault())//状态
                            .setAdinfo(addOrderRequest.getAddressInfo())
                            .setDetailInfo(addOrderRequest.getAddressDetailInfo());
                    insert = addressinfoMapper.insert(addressinfo);


                    if(insert>0){
                        gOrder.setStatus(1)
                                .setAddressId(addressinfo.getAddressid())
                                .setCheckTime(new Date())
                                .setPayWay(addOrderRequest.getPayWay());
                        int updateById = gOrderMapper.updateById(gOrder);
                        if(updateById>0){
                            result = JsonResult.success(gOrder);
                        }else{
                            result = JsonResult.fail("修改订单异常");
                        }
                    }else{
                        result = JsonResult.fail("添加地址信息异常");
                    }
                }


            }
        }else{
            result = JsonResult.fail("订单添加失败");
            System.out.println("获取添加订单数据为空");
        }
        return result;
    }

    public void delGoodsNum(int gid){
        Goods goods = goodsMapper.selectById(gid);
        goods.setGnum(goods.getGnum()-1);
        goodsMapper.updateById(goods);
    }

    @Override
    public JsonResult getAllOrder() {
        List<GOrder> gOrderList = gOrderMapper.selectList(null);
        return JsonResult.success(gOrderList);
    }

    //将地址状态置为其他
    public void updateAddress(int userId){
        List<Addressinfo> addressinfos = addressinfoMapper.selectList(Wrappers.<Addressinfo>lambdaQuery()
                .and(wrapper -> wrapper
                        .eq(Addressinfo::getUserid, userId)));
        for (Addressinfo addressinfo : addressinfos) {
            addressinfo.setDefaultStatus(0);
            addressinfoMapper.updateById(addressinfo);
        }
    }

    //订单状态：   0：生成未付款； 1：已付款； 2：待收货； 3：已完成； 4：退货状态 ;  5：订单取消
    @Override
    public JsonResult updateOrder(AddOrderRequest aoReq) {
        JsonResult result = null;
        GOrder order = gOrderMapper.selectById(aoReq.getOrderId());
        if(order!=null){
            if(aoReq.getOrderStatus()==1){ //to 付款
                order.setStatus(1);
                int update = gOrderMapper.updateById(order);
                if(update>0){
                    result = JsonResult.success(order);
                }else{
                    result = JsonResult.fail("修改失败=> 订单id: "+order.getOid());
                }

            }else if(aoReq.getOrderStatus()==2){
                order.setStatus(2);
                int update = gOrderMapper.updateById(order);
                if(update>0){
                    result = JsonResult.success(order);
                }else{
                    result = JsonResult.fail("修改失败=> 订单id: "+order.getOid());
                }

            }else if(aoReq.getOrderStatus()==3){ //确认收货
                order.setStatus(3);
                order.setComplishTime(new Date());
                int update = gOrderMapper.updateById(order);
                if(update>0){
                    result = JsonResult.success(order);
                }else{
                    result = JsonResult.fail("修改失败=> 订单id: "+order.getOid());
                }

            }else if(aoReq.getOrderStatus()==4){//退货
                order.setStatus(4);
                int update = gOrderMapper.updateById(order);
                if(update>0){
                    result = JsonResult.success(order);
                }else{
                    result = JsonResult.fail("修改失败=> 订单id: "+order.getOid());
                }

            }else if(aoReq.getOrderStatus()==5){//取消订单
                order.setStatus(5);
                int update = gOrderMapper.updateById(order);
                if(update>0){
                    result = JsonResult.success(order);
                }else{
                    result = JsonResult.fail("修改失败=> 订单id: "+order.getOid());
                }
            }
        }else{
            result = JsonResult.fail("查询订单为空");
        }
        return result;
    }

    @Override
    public JsonResult getOrderList(AddOrderRequest aoq) {

        JsonResult result = null;
        //根据用户查订单 订单列表
        //订单地址
//        Addressinfo addressinfo = addressinfoMapper.selectById(aoq.getAddressId());
        //用户订单
        List<GOrder> orders = gOrderMapper.selectList(Wrappers.<GOrder>lambdaQuery()
                .and(wrapper -> wrapper.eq(GOrder::getUid, aoq.getUserId())));
        //单个订单对象 结算页面

        List<OrderResponse> odRespList = new ArrayList<OrderResponse>();
        OrderResponse orderResponse = null;
        //待付款订单 无地址 支付时间 完成时间

        for (GOrder gOrder : orders) {
            List<OrderDetail> orderDetails = detailMapper.selectList(Wrappers.<OrderDetail>lambdaQuery()
                    .and(wrapper -> wrapper.eq(OrderDetail::getOid, gOrder.getOid())));
            //根据订单id查详情订单
            orderResponse = new OrderResponse();
            orderResponse
                    .setOrderId(gOrder.getOid())//
                    .setGoodsNum(gOrder.getGoodsNum())//
                    .setGoodsTotalPrice(gOrder.getTotalPrice())//
                    .setOrderStatus(gOrder.getStatus())//
                    .setCreateTime(gOrder.getCreateTime())//
                    .setOrderDetails(orderDetails);//
            if(gOrder.getStatus() != 0){//已付款的
                Addressinfo addressinfo = addressinfoMapper.selectById(gOrder.getAddressId());
                orderResponse.setAddressInfo(addressinfo.getAdinfo())
                        .setAddressDetailInfo(addressinfo.getDetailInfo())
                        .setUserName(orderDetails.get(0).getUsername())
                        .setUserPhone(orderDetails.get(0).getUserphone())
                        .setPayWay(gOrder.getPayWay())
                        .setCheckTime(gOrder.getCheckTime())
                        .setComplishTime(gOrder.getComplishTime());
            }
            odRespList.add(orderResponse);
        }
        if(odRespList!=null){
            result = JsonResult.success(odRespList);
        }else{
            result = JsonResult.fail("获取订单信息失败");
        }


        //订单信息
        //商品列表 List<OrderDetail> orderDetails;

        return result;
    }

    //结算页面
    @Override
    public JsonResult getCheckOrderPage(AddOrderRequest aoq) {
        JsonResult result = null;
        //用户id + (刚生成的)订单id 查询
        GOrder order = gOrderMapper.selectOne(Wrappers.<GOrder>lambdaQuery()
                .and(wrapper -> wrapper.eq(GOrder::getUid, aoq.getUserId())
                .eq(GOrder::getOid, aoq.getOrderId())));
        List<OrderDetail> orderDetails = detailMapper.selectList(Wrappers.<OrderDetail>lambdaQuery()
                .and(wrapper -> wrapper.eq(OrderDetail::getOid, order.getOid())));
        //单个订单对象 结算页面
//        OrderResponse orderResponse = new OrderResponse();
        if(orderDetails!=null){
            OrderCheckPageResponse orderCheckPageResponse = new OrderCheckPageResponse();
            orderCheckPageResponse.setOrderDetails(orderDetails)
                    .setGoodsTotalPrice(order.getTotalPrice())
                    .setGoodsNum(order.getGoodsNum())
                    .setOrderId(order.getOid());
            if(orderCheckPageResponse!=null){
                result = JsonResult.success(orderCheckPageResponse);
            }else{
                result = JsonResult.fail("获取结算页面信息失败");
            }
        }else{
            result = JsonResult.fail("获取结算页面信息失败");
        }

        return result;
    }
}
